<template>
<div class="app-container">
    <!-- START 卡片视图 START -->
    <el-card style="margin-bottom: 10px;">
        <!-- START 搜索与添加按扭区域 START -->
        <el-form ref="queryForm" :model="queryParams" :inline="true">
            <el-form-item label="请假标题" prop="title">
                <el-input
                    v-model="queryParams.title"
                    style="width: 200px"
                    size="small"
                    placeholder="请输入请假标题"
                    clearable
                    @clear="getLeaveBillList"/>
            </el-form-item>
            <el-form-item label="请假内容" prop="content">
                <el-input
                    v-model="queryParams.content"
                    style="width: 200px"
                    size="small"
                    placeholder="请输入请假内容"
                    clearable
                    @clear="getLeaveBillList"/>
            </el-form-item>
            <el-form-item label="开始时间" prop="beginTime">
                <el-date-picker
                    v-model="leaveTime"
                    size="small"
                    style="width: 260px"
                    value-format="yyyy-MM-dd"
                    type="daterange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"/>
            </el-form-item>
            <el-form-item>
                <el-button
                    icon="el-icon-search"
                    type="primary"
                    size="mini"
                    @click="getLeaveBillList">搜索
                </el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
            <el-form-item>
                <el-button v-hasPermi="['/leavebill/saveLeaveBill']" type="primary" plain size="mini" icon="el-icon-plus" @click="openAddDialog()">新增</el-button>
                <el-button v-hasPermi="['/leavebill/batchDel']" type="danger" plain size="mini" icon="el-icon-minus" @click="batchDeleteWorkFlow()">批量删除</el-button>
            </el-form-item>
        </el-form>
        <!--  END 搜索与添加按扭区域 END -->
    </el-card>
    <!-- END 卡片视图 END -->

    <!-- START 请假单表格区域 START -->
    <el-card>
        <el-table
            v-loading="listLoading"
            :data="leaveBillList"
            fit
            border
            highlight-current-row
            style="width: 100%;"
            @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" width="40" align="center" />
            <el-table-column label="请假单ID" prop="id" sortable="custom" align="center" width="110">
                <template slot-scope="{row}">
                    <span>{{ row.id }}</span>
                </template>
            </el-table-column>
            <el-table-column label="请假单标题" :show-overflow-tooltip="true" width="150px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.title }}</span>
                </template>
            </el-table-column>
            <el-table-column label="请假内容" :show-overflow-tooltip="true" width="270px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.content }}</span>
                </template>
            </el-table-column>
            <el-table-column label="天数" width="50px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.days }}</span>
                </template>
            </el-table-column>
            <el-table-column label="创建人" width="100px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.admin.name }}</span>
                </template>
            </el-table-column>
            <el-table-column label="请假时间" width="110px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.begintime }}</span>
                </template>
            </el-table-column>
            <el-table-column label="状态" align="center" width="100">
                <template slot-scope="scope">
                    <el-button v-if="scope.row.state == 0" type="primary" size="mini">未提交</el-button>
                    <el-button v-if="scope.row.state == 1" type="warning" size="mini">审批中</el-button>
                    <el-button v-if="scope.row.state == 2" type="success" size="mini">审批完成</el-button>
                    <el-button v-if="scope.row.state == 3" type="info" size="mini">已放弃</el-button>
                </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" align="center" width="300" class-name="small-padding fixed-width">
                <template slot-scope="{row,$index}">
                    <el-button v-if="row.state == 0 && row.state != 2" type="warning" icon="el-icon-check" size="mini" plain round @click="startProcess(row)">
                        提交申请
                    </el-button>
                    <el-button v-if="row.state == 0" v-hasPermi="['/leavebill/updateLeaveBill']" type="primary" icon="el-icon-edit" size="mini" plain round @click="handleUpdate(row)">
                        编辑
                    </el-button>
                    <el-button v-if="row.state != 1 && row.state != 2" v-hasPermi="['/leavebill/delLeaveBill']" size="mini" icon="el-icon-delete" type="danger" plain round @click="delLeave(row)">
                        删除
                    </el-button>
                    <el-button v-if="row.state != 0" type="success" icon="el-icon-search" size="mini" plain round>
                        审批查询
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="totalCount>0" :total="totalCount" :page.sync="queryParams.currPageNo" :limit.sync="queryParams.pageSize" @pagination="getLeaveBillList" />
    </el-card>
    <!-- END 请假单表格区域 END -->
    <!-- START 添加/编辑请假单弹出对话框窗口 START -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="680px">
        <el-form ref="dataFormRef" :rules="rules" :model="leaveBill" label-position="left">
            <el-row>
                <el-col :span="23">
                    <el-form-item label-width="90px" label="请假标题" prop="title">
                        <el-input v-model="leaveBill.title" size="medium" placeholder="请输入请假标题" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="9">
                    <el-form-item prop="begintime" label-width="90px" label="开始时间">
                        <el-date-picker
                            v-model="leaveBill.begintime"
                            value-format="yyyy-MM-dd"
                            type="date"
                            style="width: 140px"
                            placeholder="请输入请假时间"/>
                    </el-form-item>
                </el-col>
                <el-col :span="9">
                    <el-form-item prop="endtime" label-width="80px" label="结束时间">
                    <el-date-picker
                        v-model="leaveBill.endtime"
                        value-format="yyyy-MM-dd"
                        style="width: 140px"
                        type="date"
                        placeholder="请输入请假时间"
                        @blur="endtimeBlur"/>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="请假天数" label-width="80px" prop="days">
                    <el-input v-model="leaveBill.days" style="width:50px" readonly size="medium" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="23">
                    <el-form-item label="请假原因" label-width="90px" prop="content">
                        <el-input
                            v-model="leaveBill.content"
                            type="textarea"
                            :autosize="{ minRows: 2, maxRows: 6}"
                            placeholder="请输入内容"/>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="dialogStatus==='create'?insertData():updateData()">
            提交
            </el-button>
            <el-button @click="cancelEvent()">
            重置
            </el-button>
        </div>
    </el-dialog>
    <!-- END 添加/编辑请假单弹出对话框窗口  END -->
</div>
</template>
<script>
    import {getLeaveBillList,saveLeaveBill,getLeaveById,updateLeaveBill,delLeave,batchDeleteLeaveBill,startProcess} from '@/api/leavebill'
    import Pagination from '@/components/Pagination'
    export default {
        components:{
            Pagination
        },
        data:function(){
            return {
                listLoading:true,
                leaveBillList: [],
                leaveTime: [], // 请假时间
                 // 封装查询条件
                queryParams: {
                    title: '', // 请假标题
                    content: '', // 请假内容
                    beginTime: '', // 开始时间
                    endTime: '', // 结束时间
                    sort: '+id', // 排序字段
                    currPageNo: 1, // 当前页码
                    pageSize: 2 // 每页显示的数据行数
                },
                totalCount: 0, // 总记录数
                textMap: {
                    update: '编辑请假单',
                    create: '新增请假单'
                },
                // 新增和编辑对话框的状态
                dialogStatus: 'create',
                // 用于控制新增和编辑对话框的显示与隐藏
                dialogFormVisible: false,
                // 新增和编辑对话框与下面leaveBill对象进行绑定
                leaveBill: {
                    id: 0,
                    title: '',
                    content: '',
                    days: undefined,
                    begintime: '',
                    endtime: '',
                    state: 0
                },
                // 添加表单验证规则对象
                rules: {
                    title: [{ required: true, message: '请假标题必填', trigger: 'blur' }],
                    begintime: [{ required: true, message: '请假开始时间必填', trigger: 'change' }],
                    endtime: [{ required: true, message: '请假结束时间必填', trigger: 'change' }],
                    days: [{ required: true, message: '请假天数必填', trigger: 'blur' }],
                    content: [{ required: true, message: '请假原因必填', trigger: 'blur' }]
                },
                // 获取多个复选框被选中的内容(多个请假单对象)
                multipleSelection: [],
                // 获取被选中的请假单ID
                ids: []

            }
        },
        // 生命周期 - 挂载完成（可以访问DOM元素）
        mounted() {
            this.getLeaveBillList();
        },
        methods:{
            getLeaveBillList(){
                this.listLoading = true

                if(this.leaveTime!=null && this.leaveTime.length>0){
                    this.queryParams.beginTime=this.leaveTime[0];
                    this.queryParams.endTime=this.leaveTime[1];
                }

                getLeaveBillList(this.queryParams).then((res)=>{
                    this.listLoading = false
                    this.leaveBillList=res.data.list;
                    this.totalCount=res.data.totalCount
                }).catch((err)=>{
                    console.log(err);
                })
            },
            // 重置leaveBill对象
            resetLeaveBill() {
                this.leaveBill = {
                    id: 0,
                    title: '',
                    content: '',
                    days: undefined,
                    begintime: '',
                    endtime: '',
                    state: 0
                }
            },
            // 新增和修改按扭的点击事件
            openAddDialog() {
                // 重置leaveBill对象
                this.resetLeaveBill()
                this.dialogStatus = 'create'
                // 把新增/编辑对话框给显示
                this.dialogFormVisible = true
            },
            // 请假结束时间所在时间控件失去焦点事件
            endtimeBlur() {
                if (this.leaveBill.endtime) {
                    const sDate = Date.parse(this.leaveBill.begintime)
                    const eDate = Date.parse(this.leaveBill.endtime)
                    var dateSpan = Math.abs(eDate - sDate)
                    var iDays = Math.floor(dateSpan / (24 * 3600 * 1000))
                    this.leaveBill.days = iDays + 1
                }
            },
            // 取消按扭的点击事件
            cancelEvent() {
                // 重置leaveBill对象
                this.resetLeaveBill()
                // 把新增/编辑对话框给显示
                this.dialogFormVisible = false
            },
            // 新增/编辑对话框中确认按扭的点击事件(新增操作)
            insertData() {
                this.$refs.dataFormRef.validate((valid) => {
                    if (valid) {
                        // 调用leavebill.js中的saveLeaveBill方法发送请求到后端实现保存新增的请假单
                        saveLeaveBill(this.leaveBill).then((res) => {
                            // false隐藏新增请假单对话框
                            this.dialogFormVisible = false
                            if (res.code === 200) {
                                // 新增请假单信息成功后，再刷新请假单信息列表，获取最新的请假单信息
                                this.getLeaveBillList()
                                this.$message({
                                    title: '提示',
                                    message: res.message,
                                    type: 'success',
                                    duration: 2000
                                })
                            } else {
                                this.$message({
                                    title: '提示',
                                    message: res.message,
                                    type: 'error',
                                    duration: 2000
                                })
                            }
                        })
                    }
                })
            },
            // 编辑按扭的点击事件
            handleUpdate(leave) {
                // 显示编辑/添加请假单对话框
                this.dialogFormVisible = true
                // 动态修改[编辑对话框窗口标题]
                this.dialogStatus = 'update'
                // 通过请假单ID查询请假单的详情对象信息
                getLeaveById(leave.id).then((res) => {
                    this.leaveBill = res.data
                }).catch((err) => {
                    this.$message.error(err)
                })
            },
            // 编辑/添加请假单对话框中提交按扭的点击事件(修改)
            updateData() {
                updateLeaveBill(this.leaveBill).then((res) => {
                    if (res.code === 200) {
                        // 是修改成功
                        this.$message.success(res.message)
                        // 将[修改请假单弹出对话框窗口]给关闭掉
                        this.dialogFormVisible = false
                        // 修改成功后，还需要再调用getLeaveBillList()获取最新的请假单信息
                        this.getLeaveBillList()
                    } else {
                        this.$message.error(res.message)
                    }
                }).catch((err) => {
                    this.$message.error(err)
                })
            },

            delLeave(leave) {
                this.$confirm('确认要删除当前请假单信息吗?', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    delLeave(leave.id).then((res) => {
                        if (res.code === 200) {
                            // 是删除成功
                            this.$message.success(res.message)
                            // 删除成功后，获取最新的请假单列表信息
                            this.getLeaveBillList()
                        } else {
                            this.$message.error(res.message)
                        }
                    }).catch((err) => {
                        this.$message.error(err)
                    })
                }).catch(() => {
                    this.$message.info('您取消删除操作')
                })
            },
            // 当复选框被选中时，将选中的多个请假单对象multipleSelection
            handleSelectionChange(sels) {
                this.multipleSelection = sels
                console.log('选中的值', sels.map((item) => item.id))
            },
            // 批量删除按扭的点击事件
            batchDeleteWorkFlow() {
                if (this.multipleSelection && this.multipleSelection.length === 0) {
                    this.$message.info('请选择要删除的请假单信息')
                    return
                }
                // 获取复选框选中的请假单ID
                this.multipleSelection.forEach((selection) => {
                    this.ids.push(selection.id)
                })
                this.ids = this.ids.toString()
                this.$confirm('确认要批量删除当前这些请假单信息吗?', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    batchDeleteLeaveBill(this.ids).then((res) => {
                    if (res.code === 200) {
                        this.$message.success(res.message)
                        // 删除成功后，刷新请假单列表信息
                        this.getLeaveBillList()
                    } else {
                        this.$message.error(res.message)
                    }
                    }).catch((err) => {
                        this.$message.error(err)
                    })
                }).catch(() => {
                    this.$message.info('您取消了删除')
                })
            },
            startProcess(leave){
                this.$confirm('确认要提交【' + leave.title + '】请假单吗?', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    startProcess(leave.id)
                    .then((res) => {
                        if (res.code === 200) {
                            this.$message.success(res.message)
                            // 提交申请成功后，获取最新的请假单列表信息
                            this.getLeaveBillList()
                        } else {
                            this.$message.error(res.message)
                        }
                    })
                }).catch(() => {
                    this.$message.info('您取消了提交申请')
                })
            },
        }
    }
</script>
<style scoped>

</style>